package com.dmall.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.dmall.util.UploadResponse;
import com.google.gson.Gson;

/**
 * Servlet implementation class UploadPicture
 */
@WebServlet("/upc.do")
@MultipartConfig
public class UploadPicture extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UploadPicture() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//MIME,设置返回类型为json
		response.setContentType("application/json;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		//获取上传的文件
		Part part = request.getPart("file");
		//获取文件保存位置的路径
		String path  = request.getServletContext().getRealPath("/picture/");
		//获取文件名（带后缀名）
		String filename = part.getSubmittedFileName();
		//将文件写进目标位置
		part.write(path+part.getSubmittedFileName());
		//将文件信息转换成UploadResponse类对象（类似json格式的数据）
		UploadResponse urp = new UploadResponse(0,"success",filename);
		
		Gson gson = new Gson();
		//将urp类型数据转换成json
		String str = gson.toJson(urp);
		System.out.println(str);
		out.print(str);
		out.close();
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		doGet(request, response);
	}

}
